package cn.fanyc.action.blockchain.fbc.org2.controller.issue;

import cn.fanyc.action.blockchain.fbc.org2.config.GlobalConstants;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.ContractException;
import org.hyperledger.fabric.gateway.Gateway;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.nio.charset.StandardCharsets;

/**
 * 账号管理控制器
 *
 * @author Fanyc
 * @date 2020/6/18 13:59
 */
@Controller
@RequestMapping("/issue")
public class IssueUIController {

    /**
     * 模板页面文件夹
     */
    public static final String prefix = "issue";

    /**
     * Fabric网关
     */
    @Autowired
    private Gateway gateway;

    /**
     * 发布票据
     */
    @RequestMapping({"", "/", "index"})
    public String index(ModelMap modelMap) {
        return prefix + "/index";
    }

    @RequestMapping("detail/{key}")
    public String detail(ModelMap modelMap, @PathVariable String key) {
        Contract contract = gateway.getNetwork(GlobalConstants.CHANNEL_NAME).getContract(GlobalConstants.CONTRACT_FBC);
        try {
            byte[] getPapers = contract.evaluateTransaction("getPaper", key);
            JSONObject paper = new JSONObject(new String(getPapers, StandardCharsets.UTF_8));
            for (String prop : new String[]{"paperNumber", "issuer", "issueDateTime", "faceValue", "maturityDateTime", "owner", "state"}) {
                modelMap.put(prop, paper.optString(prop, ""));
            }
        } catch (ContractException e) {
            e.printStackTrace();
        }

        return prefix + "/detail";
    }
}
